package com.vframework.config.freemarker.city;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.vframework.common.model.RegionsBean;
import com.vframework.common.service.DictService;
import com.vframework.config.freemarker.CustomDirective;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

@Component
public class CityDirective extends CustomDirective {
    
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars,
            TemplateDirectiveBody body) throws TemplateException, IOException {
        if (params.isEmpty()) {
            throw new TemplateModelException("This directive doesn't allwow empty parameters.");
        }
        if (params.containsKey("pcityCode")) {
            String pcityCode = params.get("pcityCode").toString();
            List<RegionsBean> cityList = DictService.getCityList(pcityCode, "");
            env.setVariable("cityList", getBeansWrapper().wrap(cityList));
        } else if (params.containsKey("cityCode")) {
            String cityCode = params.get("cityCode").toString();
            String cityName = DictService.getCityName(cityCode);
            env.setVariable("cityName", getBeansWrapper().wrap(cityName));
        } else if (params.containsKey("cityPath")) {
            String cityCode = params.get("cityPath").toString();
            String cityName = DictService.getCityPath(cityCode);
            env.setVariable("cityPath", getBeansWrapper().wrap(cityName));
        }
        render(env, params, body);
    }

    @Override
    public void render(Environment env, Map params, TemplateDirectiveBody body) throws IOException, TemplateException {
        if (body != null) {
            body.render(env.getOut());
        } else {
            throw new RuntimeException("标签内部内容为空!");
        }
    }
}
